<?php

namespace app\common\model;

use think\Model;
use think\Session;
/**
 * 关键词
 */
class Keywords Extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = 'updated_at';
    // 追加属性
    protected $append = [
    	'keyword'
    ];
    public function getKeywordAttr($value,$data=[],$wechat_id=null){
    	$keywords = [];
    	if(isset($data['id']) && intval($data['id']) > 0){
            $wechat_id = intval($wechat_id) > 0 ? $wechat_id : Session::get('wechat_id');
    		$keywords = db('keyword_mate')->where('wechat_id',intval($wechat_id))->where('keyword_id',$data['id'])->column('keyword');
    	}
    	return is_array($keywords) ? $keywords : [];
    }
    // 获取关键词
    public function getKeywordItem($keyword=null,$wechat_id=0){
        // 咨询标题完全匹配
        $result = db('keywords')->alias('m')
                ->join('keywork_wechat a',"a.keywork_id = m.id")
                ->field("m.*")
                ->where('m.name',$keyword)
                ->where('a.wechat_id',$wechat_id)
                ->select();
        if(!empty($result)){
            return $result;
        }
        // 关键词完全匹配
        $keywordIds = db('keyword_mate')->where('wechat_id',intval($wechat_id))->where(['keyword'=>$keyword])->column('keyword_id');
        if(is_array($keywordIds)){
            $result = db('keywords')->where('id','in',$keywordIds )->select();
            if(!empty($result) && is_array($result)){
                return $result;
            }
        }
        // 关键词模糊匹配
        $keywordIds = db('keyword_mate')->where('wechat_id',intval($wechat_id))->where(['keyword'=>['like',"%".$keyword."%"]])->column('keyword_id');
        if(is_array($keywordIds)){
            $result = db('keywords')->where('id','in',$keywordIds )->select();
            if(!empty($result) && is_array($result)){
                return $result;
            }
        }
        return false;
    }
}
